<template>
  <div class="BBCCGGSQ Editor" >
    <el-dialog :title="dialogTitle" :visible="dialogVisible"  @close="close" width="75%">
      <el-form :gutter="24"  :model="param" :rules="rules" ref="param" :inline="true"  label-width="165px" class="demo-ruleForm">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="线路:" prop="lineCode" style="margin-bottom:10px">
              <el-select v-model="param.lineCode" placeholder="请选择"  :disabled="true" clearable>
                <el-option
                  v-for="(item,index) in lineCodes"
                  :key="index"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点:" prop="stationCode" style="margin-bottom:10px">
              <el-select v-model="param.stationCode"  :disabled="true" clearable>
                <el-option
                  v-for="(item,index) in stationCodes"
                  :key="index"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="差错类别:" prop="errorClassification" style="margin-bottom:10px">
              <el-select v-model="param.errorClassification"  :disabled="showType==4" clearable>
                <el-option value="1" label="填写错误"></el-option>
                <el-option value="2" label="系统错误"></el-option>
                <el-option value="3" label="提交错误"></el-option>
              </el-select>
            </el-form-item>
          </el-col>	 
          <!-- <el-col :span="12">
            <el-form-item prop="errorAmount" label="差错金额:">
              <el-input-number v-model="param.errorAmount" controls-position="right" :disabled="showType==4" :precision="2" clearable></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="互联网购票机编号:" prop="equipmentCode" style="margin-bottom:10px">
              <el-select v-model="param.equipmentCode" @change="select_status" :disabled="showType==4" filterable clearable placeholder="请选择">
                <el-option v-for="(item,index) in equipmentCodes"
                           :value="item.equipmentCode" :label="item.equipmentCode" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="reportNameId" label="报表名称:" style="margin-bottom:10px">
              <el-select v-model="param.reportNameId" placeholder="报表名称" :disabled="showType==4" clearable>
                <el-option
                  v-for="(item,index) in reportNameIds"
                  :key="index"
                  :label="item.reportName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报表日期:" prop="reprotTime" style="margin-bottom:10px">
              <el-date-picker type="date" placeholder="报表日期" v-model="param.reprotTime" :disabled="showType==4" value-format="yyyy-MM-dd" clearable></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="tvm编号:" prop="tvmCode" style="margin-bottom:10px">
              <el-select v-model="param.tvmCode" placeholder="请选择"  filterable :disabled="showType==4" clearable>
                <el-option
                  v-for="(item,index) in tvmCodes"
                  :key="index"
                  :label="item.tvmCode"
                  :value="item.tvmCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备操作号:" prop="deviceNo" style="margin-bottom:10px">
              <el-select v-model="param.deviceNo" placeholder="请选择" filterable :disabled="showType==4" clearable>
                <el-option
                  v-for="(item,index) in equipmentNumberList"
                  :key="index"
                  :label="item.operationCode"
                  :value="item.operationCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="bom编号:" prop="bomCode" style="margin-bottom:10px">
              <BomCodeSelect v-model="param.bomCode" :disabled="showType==4"></BomCodeSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="钱箱类型:" prop="cashboxType" style="margin-bottom:10px">
              <el-select v-model="param.cashboxType" :disabled="showType==4" clearable>
                <el-option v-for="(item,index) in getMappingStatusArray('stm_cash_box_type')"
                           :value="item.value" :label="item.label" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" >
          <el-col :span="12">
            <el-form-item label="结算开始日期:" prop="settleBeginTime" style="margin-bottom:10px">
              <el-date-picker type="date" placeholder="结算开始日期" v-model="param.settleBeginTime" :disabled="showType==4" value-format="yyyy-MM-dd" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算结束日期:" prop="settleEndTime" style="margin-bottom:10px">
              <el-date-picker type="date" placeholder="结算结束日期" v-model="param.settleEndTime" :disabled="showType==4" value-format="yyyy-MM-dd" clearable></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <!-- <el-col :span="12">
            <el-form-item label="钱箱编号:" prop="cashboxCode" >
              <el-select v-model="param.cashboxCode" :disabled="showType==4" clearable placeholder="请选择">
                <el-option v-for="(item,index) in tvmCashBoxCodes"
                           :value="item.cashbox_code" :label="item.cashbox_code" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="修改期限:" prop="modifyLimitTime" style="margin-bottom:10px">
              <el-input v-model="param.modifyLimitTime" placeholder="请输入内容" :disabled="showType==2 || showType==3 || showType==4" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="旧卡号:" prop="cardNo" style="margin-bottom:10px">
              <el-input v-model="param.cardNo" placeholder="请输入旧卡号" :disabled="showType==4" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
	 <el-row :gutter="24">  
	    <el-col :span="12">
            <el-form-item label="值班站长:" prop="dutyStationLeaderName" style="margin-bottom:10px">
              <el-input v-model="param.dutyStationLeaderName"   :disabled="showType==4" clearable></el-input>
            </el-form-item>
          </el-col>    
           <el-col :span="12">
            <el-form-item label="值班站长工号:" prop="dutyStationLeaderCode" style="margin-bottom:10px">
              <el-input v-model="param.dutyStationLeaderCode"  :disabled="showType==4" clearable></el-input>
            </el-form-item>
          </el-col>
	      
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="申请原因:" style="margin-bottom:10px">
              <el-input style="width: 500px" type="textarea" v-model="param.applyReason" :disabled="showType==4" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <div>
            <el-button type="danger" :disabled="showType==4" @click="del()" size="mini" style="float: right;margin-left: 10px">删除</el-button>
            <el-button type="primary" :disabled="showType==4" @click="add()" size="mini" style="float: right;">新增</el-button>
          </div>
          <avue-crud
            class="Editor list"
            ref="crud"
            :option="optionList"
            @selection-change="selectionChange"
            :data="tableData"
          >
            <template slot-scope="scope" slot="stationPersonrId">
              <el-select v-model="scope.row.stationPersonrId" placeholder="请选择" style="width: 150px" @change="changeStationPersonrId(scope.row,$event)" :disabled="showType==4" filterable>
                <el-option
                  v-for="(item,index) in sheJiPersons"
                  :key="index"
                  :label="item.nikename"
                  :value="item.userId">
                </el-option>
              </el-select>
            </template>
            <template slot-scope="scope" slot="stationPersonrCode">
              {{scope.row.stationPersonrCode}}
            </template>
          </avue-crud>
        </el-row>
        <br/>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注:" >
              <el-input style="width: 500px" type="textarea" v-model="param.remark" :disabled="showType==4"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <br/>
        <br/>
        <el-row :gutter="24" style="text-align: center">
            <el-form-item>
              <el-button type="primary" @click="handleSubmit()" v-if="(showType==2 || showType==4) && applyForType ==1">保存</el-button>
              <el-button type="primary" @click="addData()" v-if="showType==3 && applyForType ==1">保存</el-button>
              <el-button type="primary" @click="addAndSubmitData()" v-if="showType==3 && applyForType ==2">保存</el-button>
              <el-button @click="close()" style="margin-left: 30px" >返回</el-button>
            </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>


<script>
    import {getForm, postForm} from '@/api/gen/gen'
    import moment from "moment";
    import {
      getgetStationCodes,
      getLineCodes,
      getPersonRole,
      getSwPmDeviceOperationCodeList,
      getSwPmReportPath,
      getUserDataByJobNo,
      getSwPmTvmCodeList,
      getMappingStatusArray, getLineAllAsyn, getReplayPeriod,
      getSwPmInternetTicketEquipmentCodeList,
      getLineAndStationByCode, getSysUserToLS
    } from "../../../../../api/subwayRat/commonCheck";
    import {
      get_xw_SwStReportErrorAlterAppayDetail,
      optionList, update_xw_ReportError,
    } from "../../../../../api/stationTiecketManager/xianWngCJXXQR/BBCCGG/XWBBCCGGTZ/KZDLCK";
    import {add_xw_sq_ReportError,addAndSubmit_xw_sq_ReportError} from "../../../../../api/stationTiecketManager/xianWngCJXXQR/BBCCGG/BBCCGGSQ/KZDLCK";
    import {addReportError} from "../../../../../api/subwayRat/reportMondify/reportMistakeInfo";
    import {checkparam} from "./checkparam";
    import BomCodeSelect from './BomCodeSelect';
    export default {
      components:{
        BomCodeSelect
      },
        data() {
            return {
              isModify:'',
              showType:3,//4审批通过的编辑，3添加，2编辑，1预览
              dialogTitle:'', //弹框标题
              dialogVisible:false,
              optionList:optionList(),
              tableData:[],
              reportNameIds:[],
              lineCodes:[],
              stationCodes:[],
              tvmCodes:[],
              //tvmCashBoxCodes:[],
              equipmentNumberList:[],
              equipmentCodes: [],
              dutyStationLeaderIds:[],
              dutyStationPersonIds:[],
              stationPersonIds:[],
              sheJiPersons:[], //涉及人员
              multipleSelectionRows:[],
              multipleSelectionKeys:[],
              param:{
                //errorClassification:'',
                errorAmount:'',
                modifyTime:'',
                reportNameId:'',
                applyReason:'',
                remark:'',
                isModify:'',
                bomCode:'',
                //cashboxCode:'',
                cashboxType:'',
                modifyLimitTime:'',
                equipmentCode: '',
                diffAmountId: '',
                dataSourceTable: '',
                dataSource: '',
                cardNo: ''
              },
              applyForType: 1,
              pages:{},
              rules: {
                applyReason: [
                  { required: true, message: '非空', trigger: 'blur' }
                ],
                dutyStationLeaderId: [
                  { required: true, message: '非空', trigger: 'blur' }
                ],
                dutyStationPersonId: [
                  { required: true, message: '非空', trigger: 'blur' }
                ],
                stationPersonId: [
                  { required: true, message: '非空', trigger: 'blur' }
                ],
                lineCode: [
                  { required: true, message: '非空', trigger: 'blur' }
                ],
                stationCode: [
                  { required: true, message: '非空', trigger: 'blur' }
                ],
                reprotTime: [
                  { required: true, message: '非空', trigger: 'blur' }
                ],
                reportNameId: [ //报表名称
                  { required: true, message: '非空', trigger: 'change' }
                ],
                // settleBeginTime: [
                //   { required: true, message: '非空', trigger: 'blur' }
                // ],
                // settleEndTime: [
                //   { required: true, message: '非空', trigger: 'blur' }
                // ],
                errorDetail: [
                  { required: true, message: '非空', trigger: 'blur' }
                ],
                // errorAmount:[
                //   { required: true, message: '非空', trigger: 'blur' }
                // ],
                errorClassification: [ //差错类别
                  { required: true, message: '非空', trigger: 'change' }
                ],
                modifyTime: [
                  { required: true, message: '非空', trigger: 'blur'}
                ],
                // isModify: [
                //   { required: true, message: '非空', trigger: 'blur'}
                // ],
              }
            }
        },
        created() {

        },
        methods: {
          moment,getMappingStatusArray,
          select_status(val){
            this.$forceUpdate();
          },
          async others_report_add_call(param){ //其它页面添加报表差错
            this.applyForType = 2;
            this.dialogTitle = param.dialogTitle;
            this.pages = param.page;
            let th=this;
            th.clearParam();
            th.isModify='0';
            this.initData(param);
            this.getPersonRoles(param.lineCode,param.stationCode);
            let alter_limit=await getReplayPeriod();
            th.param.modifyLimitTime=alter_limit.data.data.ALTER_limit;
            th.dialogVisible=true;
            Object.assign(th.param,param);
            this.showType=param.showType;
            let users=await getUserDataByJobNo({userCodes:param.userCodes});
            this.tableData=[];
            for(let i=0;i<users.data.length;i++){
              this.tableData.push({stationPersonrId:users.data[i].userId,
                stationPersonrCode:users.data[i].userCode,
                stationPersonrName:users.data[i].nikename,
              });
            }
          },
          async addAndSubmitData(){
            let th=this;
            if(this.param.errorClassification == undefined || this.param.errorClassification==''){
              this.$message({message: '差错类别不能为空',type: 'error'});
              return;
            }
            if(this.param.reportNameId == undefined || this.param.reportNameId==''){
              this.$message({message: '报表名称不能为空',type: 'error'});
              return;
            }
            let is= checkparam(this);
            if(!is){
                return;
            }
            let messageLSList = [];
            let data = await getLineAndStationByCode({"lineCode":this.param.lineCode, "code":this.param.stationCode});
            messageLSList.push({
              "content":"车站：" + data.data[0].name,
              "lineCode":this.param.lineCode,
              "stationCode":this.param.stationCode
            })

            let type = 'reportSubmit_001';
            let roleCode = 29;
            if (this.param.reportNameId == '12' || this.param.reportNameId == '14') {
              type = 'reportSubmit_002';
              roleCode = 16;
            }
            let title = this.param.reprotTime + this.$store.getters.tag.label
            let p = {
              messageLSList:JSON.stringify(messageLSList),
              title:title,
              msgType:"审批",
              type:type,
              roleCode: roleCode
            };
            this.$refs.param.validate((valid) => {
              if (valid) {
                this.$confirm('是否确定要保存并提交，提交后不可以再修改？', '提示', {
                  confirmButtonText: '是',
                  cancelButtonText: '否',
                  type: 'warning'
                }).then(() => {
                  // th.param.lineCode=this.$store.getters.userInfo.lineCode;
                  // th.param.stationCode = th.$store.getters.userInfo.stationCode;
                  th.param.isModify = th.isModify;
                  // let param=JSON.stringify(th.param);
                  // let datas=JSON.stringify(th.tableData);
                  // let data2=JSON.stringify(p);
                  let params = {
                    row:JSON.stringify(th.param),
                    sheJiPersons:JSON.stringify(th.tableData),
                    param:JSON.stringify(p)
                  }
                  //addAndSubmit_xw_sq_ReportError({row:param,sheJiPersons:datas,param:data2}).then(res=>{
                  addAndSubmit_xw_sq_ReportError(params).then(res=>{
                    this.close();
                    this.$message({
                      message: res.data.code==0?'操作成功':'操作失败',
                      type: res.data.code==0?'success':'error',
                    });
                    if(this.param.reportNameId=='12' || this.param.reportNameId=='14'){
                      this.$parent.searchChange();
                    }else{
                      this.$parent.getList(this.pages);
                    }
                  })
                });
              } else {
                return false;
              }
            });
          },
          add(){
            this.tableData.push({$cellEdit:true});
          },
          del(){
            for(let i=0;i<this.multipleSelectionRows.length;i++){
              this.tableData.splice(this.multipleSelectionRows[i].$index,1);
            }
          },
          handleSubmit() {           

            let param=JSON.stringify(this.param);
            let datas=JSON.stringify(this.tableData);
            update_xw_ReportError({row:param,sheJiPersons:datas}).then((res)=>{
              this.$parent.search();
                  this.close();
                  this.$message({
                    message: res.data.code==0?'操作成功':'操作失败',
                    type: res.data.code==0?'success':'error',
                  });
                })
            
          },
          addData(){
            let th=this;
            if(this.param.errorClassification == undefined || this.param.errorClassification==''){
              this.$message({message: '差错类别不能为空',type: 'error'});
              return;
            }
            if(this.param.reportNameId == undefined || this.param.reportNameId==''){
              this.$message({message: '报表名称不能为空',type: 'error'});
              return;
            }           
           let is= checkparam(this);
            if(!is){
                return;
            }
            this.$refs.param.validate((valid) => {
              if (valid) {
                th.param.lineCode=this.$store.getters.userInfo.lineCode;
                th.param.stationCode = th.$store.getters.userInfo.stationCode;
                th.param.isModify = th.isModify;
                let param=JSON.stringify(th.param);
                let datas=JSON.stringify(th.tableData);
                add_xw_sq_ReportError({row:param,sheJiPersons:datas}).then(res=>{
                  this.close();
                  this.$message({
                    message: res.data.code==0?'操作成功':'操作失败',
                    type: res.data.code==0?'success':'error',
                  });
                  this.$parent.search();
                })
              } else {
                return false;
              }
            });
           
          },
         async previewEditor(row,showType,title){
            this.dialogTitle=title;
            this.showType=showType;
            this.dialogVisible=true;
            this.clearParam();
            if(showType==3){
              this.isModify=0+'';
              this.tableData=[];
              let line_code=this.$store.getters.userInfo.lineCode;
              let station_code = this.$store.getters.userInfo.stationCode;
              this.initData({lineCode:line_code,stationCode:station_code});
              this.getPersonRoles(line_code,station_code);
              Object.assign(this.param,{lineCode:line_code,stationCode:station_code});
              let alter_limit=await getReplayPeriod();
              this.param.modifyLimitTime=alter_limit.data.data.ALTER_limit;
              return;
            }else{
              row.reportNameId=Number(row.reportNameId);
              this.getSheJIPerson(row);
              this.getPersonRoles(row.lineCode,row.stationCode);
              this.initData(row);
              Object.assign(this.param,row);
            }
          },
          getPersonRoles(line_code,station_code){
            this.sheJiPersons=[];
            getSysUserToLS({lineCode:line_code,stationCode:station_code}).then(res=>{
              this.stationPersonIds=res.data.data;
              this.sheJiPersons=this.sheJiPersons.concat(this.stationPersonIds);
            })          

          },
          initReportNameIds(){ //初始化报表名
            getSwPmReportPath().then(res=>{
              this.reportNameIds=res.data.data;
            })
          },
          getUserCode(id,users,codeVar){           
            for(let i=0;i<users.length;i++){
              if(users[i].userId==id){
                this.param[codeVar]=users[i].userCode;
              }
            }
          },
          changeStationPersonrId(row,id){
            for(let i=0;i<this.sheJiPersons.length;i++){
              if(this.sheJiPersons[i].userId==id){
                row.stationPersonrName=this.sheJiPersons[i].nikename;
                row.stationPersonrCode=this.sheJiPersons[i].userCode;
                return;
              }
            }
          },
          getSheJIPerson(row){ //涉及人员
            //获取涉及人员
            get_xw_SwStReportErrorAlterAppayDetail({relationid:row.id}).then(res=>{
              this.tableData=res.data.data;
            })
          },
          getTvmCodes(){//获取tvmCode
            let param={};
            param.lineCode=this.searchForm.lineCode;
            param.stationCode=v;
            getSwPmTvmCodeList(param).then(r=>{
              this.tvmCodes=r.data;
            });
          },
          
          getEquipmentCode(param,isClear){
            let p={};
            p.lineCode=param.lineCode;
            p.stationCode=param.stationCode;
            getSwPmInternetTicketEquipmentCodeList(p).then(r=> {
              this.equipmentCodes = r.data.data;
              if(isClear){
                this.param.equipmentCode='';
              }
            });
          },
          close(){
            this.$refs.param.resetFields();
            this.dialogVisible=false;
          },
          clearParam(){
            this.param={
              applyReason:"",
              remark:'',
              id:'',
              lineCode:"",
              stationCode:'',
              reprotTime:moment().format("YYYY-MM-DD"),
              reportNameId:"",
              dutyStationLeaderId:"",
              dutyStationLeaderCode:"",
	      dutyStationLeaderName:"",
              dutyStationPersonId:"",
              dutyStationPersonCode:"",
              stationPersonId:"",
              stationpPersonCode:"",
              settleBeginTime:moment().format("YYYY-MM-DD"),
              settleEndTime:moment().format("YYYY-MM-DD"),
              errorDetail:'',
              errorClassification:'1',
              bomCode:'',
              //cashboxCode:'',
              cashboxType:'',
              modifyLimitTime:'',
              tvmCode:'',
              deviceNo:'',
              errorAmount:'',
              cardNo:''
            };
          },
          selectionChange(list){
            this.multipleSelectionRows=list;
            this.multipleSelectionKeys=[];
            for(let i=0;i<list.length;i++){
              this.multipleSelectionKeys.push(list[i].id);
            }
          },
          async initData(row){
            await getLineAllAsyn().then(res=>{ //获取线路
              this.lineCodes=res.data;
            });
            await getgetStationCodes(row.lineCode).then(res=>{
              this.stationCodes=res;
            });
            let param={};
            param.lineCode=row.lineCode;
            param.stationCode=row.stationCode;
            getSwPmTvmCodeList(param).then(r=>{
              this.tvmCodes=r.data;
            });           
            this.getEquipmentCode(param);
            getSwPmDeviceOperationCodeList(param).then(r=> {
              this.equipmentNumberList = r.data.data;
            });
          }
        },
      mounted() {
          this.initReportNameIds();

      }
    }
</script>
<style >
  .Editor.list .avue-crud__tip.el-tag{
        display: none;
  }
</style>
